/*
    5. Write a program in C to count the total number of words in a string. 

    Test Data :
    Input the string : This is w3resource.com

    Expected Output :

    Total number of words in the string is : 3 
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char* getStr(char *str)
{
    char ch;
    char *p = str;
    while((ch = getchar()) != '\n'){
        *p = ch;
        p++;
    }
    *p = '\0';
    return str;
}

int getStrLen(char *str)
{
    int len = 0;
    char *p = str;
    while(*p != '\0'){
        len++;
        p++;
    }
    len++; // '\0'
    return len;
}

int getNumOfWords(char *str)
{
    int in = 0, out = 0;
    int cnt = 0;
    while(*str != '\0'){
        if(isalpha(*str) && in == 0){
            in = 1;
        }
        if(!isalpha(*str) && in == 1){
            out = 1;
        }
        if(in == 1 && out == 1){
            cnt++;
            in = out = 0;
        }
        str++;
    }
    if(in) cnt++;
    return cnt;
}

int main(void)
{
    char *str = malloc(1024);
    int i = 0, len;
    printf("Input the string : ");
    getStr(str);  
    printf("Total number of words in the string is : %d", getNumOfWords(str));

    return 0;
}